//
//  SSUserModel.swift
//  weibo
//
//  Created by 邵帅 on 16/6/24.
//  Copyright © 2016年 groupNineObject. All rights reserved.
/*
 "access_token": "ACCESS_TOKEN",
 "expires_in": 1234,
 "remind_in":"798114",
 "uid":"12341234"
 */

import UIKit

class SSUserModel: NSObject, NSCoding{

    var access_token : String?
    
    var expires_in : NSTimeInterval = 0 {
        
        didSet {
            
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
 
    // 过期日期
    var expires_date: NSDate?
    
    var remind_in : String?
    var uid : String?
    var screen_name : String?
    var profile_image_url : String?
    
    
    init(dict : [String : AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }

    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    // 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(remind_in, forKey: "remind_in")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(profile_image_url, forKey: "profile_image_url")
        
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        remind_in = aDecoder.decodeObjectForKey("remind_in") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        profile_image_url = aDecoder.decodeObjectForKey("profile_image_url") as? String
        
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    // 提供一个归档方法
    func saveModel(){
        
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent("aaa.bbb")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    
    
    // 提供一个解档的方法
    class func readModel()-> SSUserModel? {
        
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent("aaa.bbb")
        
        let userModel = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath)as? SSUserModel
        
        if let date = userModel?.expires_date {
            
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return userModel
            } else {
                return nil
            }
            
        }
        
        return userModel
    }
    
}
